package com.cqkqinfo.websocket.test;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.client.WebSocketConnectionManager;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.annotation.PostConstruct;
import java.io.IOException;

@Slf4j
@Component
public class WebSocketClient {


    private final WebSocketConnectionManager connectionManager;
    private WebSocketSession session;

    public WebSocketClient() {
        StandardWebSocketClient client = new StandardWebSocketClient();
        WebSocketHandler webSocketHandler = new TextWebSocketHandler() {

            @Override
            public void afterConnectionEstablished(WebSocketSession session) {
                WebSocketClient.this.session = session;
            }

            @Override
            public void handleTextMessage(WebSocketSession session, TextMessage message) {
                // 在这里处理从服务端发送过来的消息
                String result = message.getPayload();
                log.info("客户端收到消息：{}", result);
                /*if ("HEARTBEAT".equals(message.getPayload())) {
                    try {
                        session.sendMessage(new TextMessage("HEARTBEAT_ACK"));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {

                    try {
                        session.sendMessage(new TextMessage(result));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }*/
            }
        };
        this.connectionManager = new WebSocketConnectionManager(client, webSocketHandler, "ws://localhost:8080/websocket");
    }

    @PostConstruct
    public void start() {
        connectionManager.start();
    }

    @Scheduled(fixedDelay = 10000)
    public void sendHeartBeat() {
        if (session != null && session.isOpen()) {
            try {
                session.sendMessage(new TextMessage("HEARTBEAT"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            connectionManager.stop();
            connectionManager.start();
        }
    }
}
